import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, InputNumber, TreeSelect, Select, message } from 'antd';
import { addDept, updateDept, getDeptInfo, getTreeDepts } from '../services';
import { Dept } from '../type';

interface Props {
  open: boolean;
  dept: Dept | null;
  onCancel: () => void;
  onOk: () => void;
}

const DeptFormModal: React.FC<Props> = ({ open, dept, onCancel, onOk }) => {
  const [form] = Form.useForm();
  const [deptTree, setDeptTree] = useState<Dept[]>([]);

  const loadDeptTree = async () => {
    const res = await getTreeDepts();
    setDeptTree(res.data);
  };

  useEffect(() => {
    if (open) {
      loadDeptTree();
      if (dept && dept.id) {
        getDeptInfo(dept.id).then(res => {
          form.setFieldsValue(res.data);
        });
      } else {
        form.resetFields();
        form.setFieldsValue({ status: '1', parentId: 0 });
      }
    }
  }, [open, dept]);

  const handleSubmit = async () => {
    const values = await form.validateFields();
    if (dept?.id) {
      await updateDept({ ...values, id: dept.id });
      message.success('修改成功');
    } else {
      await addDept(values);
      message.success('新增成功');
    }
    onOk();
  };

  return (
    <Modal
      open={open}
      title={dept?.id ? '编辑部门' : '新增部门'}
      onCancel={onCancel}
      onOk={handleSubmit}
      destroyOnClose
    >
      <Form form={form} layout="vertical">
        <Form.Item name="deptName" label="部门名称" rules={[{ required: true, message: '请输入部门名称' }]}> 
          <Input placeholder="请输入部门名称" />
        </Form.Item>

        <Form.Item name="parentId" label="上级部门">
          <TreeSelect
            treeData={deptTree}
            fieldNames={{ label: 'deptName', value: 'id' }}
            placeholder="请选择上级部门"
            allowClear
            treeDefaultExpandAll
          />
        </Form.Item>

        <Form.Item name="orderNum" label="显示排序">
          <InputNumber min={0} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item name="leader" label="负责人">
          <Input placeholder="请输入负责人" />
        </Form.Item>

        <Form.Item name="phone" label="联系电话">
          <Input placeholder="请输入联系电话" />
        </Form.Item>

        <Form.Item name="status" label="状态">
          <Select>
            <Select.Option value="1">正常</Select.Option>
            <Select.Option value="0">停用</Select.Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default DeptFormModal;
